import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user-student'
import { useServerUserStore } from '@/stores'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path:'/imitate-login',
      name:'模拟登录', 
      component: () => import('@/views/sever/ImitateLogin.vue'), 
    },
    // { path:'/login', component: () => import('@/views/login/MyLogin.vue') },
    // { path:'/',redirect:'/server'},
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/client/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      redirect: '/exam'
    },
    {
      path: '/exam',
      component: () => import('@/views/client/Layout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: 'list',
          name: 'ExamList',
          component: () => import('@/views/client/exam/List.vue')
        },
        {
          path: ':id',
          name: 'ExamDetail',
          component: () => import('@/views/client/exam/Detail.vue')
        },
        {
          path: ':id/take',
          name: 'ExamTake',
          component: () => import('@/views/client/exam/Take.vue')
        }
      ]
    },
    {
      path: '/server',
      name: '服务端布局',
      component: () => import('@/views/sever/ServerLayout.vue'),
      children: [
        {
          path: 'review-task-scheduling',
          name: '评阅任务调度',
          component: () => import('@/views/sever/ReviewTaskScheduling.vue'),
          meta: {
            requiresAuth: true,
            requiredRoleId: 2, // 学科组长权限
          }
        },
        {
          path: 'task-manage',
          name: '评阅任务管理',
          component: () => import('@/views/sever/TaskManage.vue'),
        },
        {
          path: 'test',
          name: '试卷批阅',
          component: () => import('@/views/sever/Test.vue'),
        },
        {
          path: 'recheck-request',
          name: '查卷申请',
          component: () => import('@/views/sever/recheckRequest/RecheckRequest.vue'),
          meta: {
            requiresAuth: true,
            requiredRoleId: 3, // 教师
          }
        },
        {
          path: 'recheck-request-manage',
          name: '查卷申请管理',
          component: () => import('@/views/sever/recheckRequestManage/RecheckRequestManage.vue'),
          meta: {
            requiresAuth: true,
            requiredRoleId: 2, // 学科组长
          }
        },
        {
          path: 'recheck-task',
          name: '复查任务',
          component: () => import('@/views/sever/recheckTask/RecheckTask.vue'),
        },
        {
          path: 'backup-data',
          name: '备份数据',
          component: () => import('@/views/sever/backupData/BackupComponent.vue'),
        },
        {
          path: 'score-analysis-export',
          name: '成绩分析与导出',
          component: () => import('@/views/sever/scoreAnalysisExport/ScoreAnalysisExport.vue'),
        } 
      ]
    },
    {
      path: '/whole-paper-review',
      name: '整张试卷批阅',
      component: () => import('@/views/sever/WholePaperReview.vue'),
    },
    {
      path: '/single-question-review',
      name: '单道大题批阅',
      component: () => import('@/views/sever/SingleQuestionReview.vue'),
    },
    {
      path: '/recheck-component',
      name: '复查界面',
      component: () => import('@/views/sever/recheckTask/RecheckComponent.vue'),
    },
    {
      path: '/score-analysis',
      name: '成绩分析',
      component: () => import('@/views/sever/scoreAnalysisExport/scoreAnalysis.vue'),
    },
    {
      path: '/score',
      component: () => import('@/views/client/Layout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: 'list',
          name: 'ScoreList',
          component: () => import('@/views/client/score/List.vue')
        },
        {
          path: ':id',
          name: 'ScoreDetail',
          component: () => import('@/views/client/score/Detail.vue')
        }
      ]
    },
    {
      path: '/change-machine',
      name: 'ChangeMachine',
      component: () => import('@/views/client/ChangeMachine.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'Profile',
      component: () => import('@/views/client/Profile.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/client/NotFound.vue')
    }
  ]
})

/**
 * 全局路由守卫
 * 处理登录验证和路由重定向
 */
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  console.log(userStore.token);
  
  // 检查是否需要登录且用户未登录
  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    // 重定向到登录页
    next({ 
      path: '/login', 
      query: { redirect: to.fullPath } // 保存原始目标路径
    })
  } 
  // 已登录用户访问登录页时重定向到首页
  else if (to.path === '/login' && userStore.isAuthenticated) {
    next('/exam/list')
  } 
  // 其他情况正常通过
  else {
    next()
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useServerUserStore()
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 如果未登录，需要先登录
    if (!userStore.token) {
      ElMessage.error('请先登录')
      // 重定向到登录页面，此处需要替换为真实的登录路由
      // next('/login')
      next(false)
      return
    }
    
    // 检查是否有特定角色权限要求
    if (to.meta.requiredRoleId !== undefined) {
      const hasRequiredRole = userStore.userInfo?.roleId === to.meta.requiredRoleId
      
      if (!hasRequiredRole) {
        ElMessage.error('您没有权限访问该页面')
        next(false)
        return
      }
    }
  }
  
  // 通过权限验证，放行
  next()
  console.log('放行了！')
})

export default router
